import axios, { AxiosRequestConfig } from "axios";
import { BASE_URL } from "./config";
import type {
  ReturnImageInfosObj,
  ImageReturnInfo,
  ReturnAbracadabraInfosObj,
  AbracadabraReturnInfo,
} from "@/types";

// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  baseURL: BASE_URL,
  // 超时
  timeout: 20000,
});

// request拦截器
service.interceptors.request.use(
  (requestConfig: any) => {
    return requestConfig;
  },
  (error) => {
    console.log(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res) => {
    let useInterceptorsFlag: string = import.meta.env
      .VITE_USE_RESPONSE_INTERCEPTORS;
    if (useInterceptorsFlag == "true") {
      if (typeof res.data === "string") {
        res.data =
          "https://img1.ali213.net/glpic/2022/09/01/584_20220901115153820.png";
      }
      try {
        (res.data as ReturnImageInfosObj).picture_infos.forEach(
          (infoItem: ImageReturnInfo) => {
            infoItem.url =
              "https://img1.ali213.net/glpic/2022/09/01/584_20220901115153820.png";
          }
        );
      } catch (e) {
        console.log(e);
      }
      try {
        (res.data as ReturnAbracadabraInfosObj).abracadabra_infos.forEach(
          (itemItem: AbracadabraReturnInfo) => {
            itemItem.sample_image_url =
              "https://img1.ali213.net/glpic/2022/09/01/584_20220901115153820.png";
          }
        );
      } catch (e) {
        console.log(e);
      }
    }

    return res;
  },
  (error) => {
    Promise.reject(error);
  }
);

export default service;
